package com.graduation.work.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.client.CmnClient;
import com.graduation.model.entity.Dict;
import com.graduation.model.entity.Enterprise;
import com.graduation.model.vo.EnterpriseVo;
import com.graduation.work.mapper.EnterpriseMapper;
import com.graduation.work.service.EnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 企业信息表 服务实现类
 * </p>
 *
 * @author tianwenle
 * @since 2023-02-16
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {


    @Autowired
    private CmnClient cmnClient;

    @Override
    public List<EnterpriseVo> getAllEnvType() {
        // 查询所有的企业类型数据
        List<EnterpriseVo> list = new ArrayList<>();
        // 获取当前类型下的所有数据
        List<Dict> dicts = cmnClient.getAllDataType(8L);
        // 遍历赋值
        for (Dict dict : dicts) {
            EnterpriseVo enterpriseVo = new EnterpriseVo();
            enterpriseVo.setLabel(dict.getName());
            enterpriseVo.setValue(dict.getId() + "");
            list.add(enterpriseVo);
        }

        return list;
    }

    @Override
    public void insertEnv(Enterprise enterprise) {
        // 判断类型是否传输进来了
        if (enterprise.getEnvStr() != null && !"".equalsIgnoreCase(enterprise.getEnvStr())){
            // 如果长度为3 正好为类型的编号
            if (enterprise.getEnvStr().length() == 3){
                // 对类型编号重新赋值
                enterprise.setOrgtype(enterprise.getEnvStr());
                // 如果之前添加过 这里就是修改
                // 这里应该判断统一社会编号
                QueryWrapper<Enterprise> wrapper = new QueryWrapper<>();
                wrapper.eq("code",enterprise.getCode());
                Enterprise dbEnterprise = baseMapper.selectOne(wrapper);
                if (dbEnterprise != null && Objects.equals(enterprise.getCode(), dbEnterprise.getCode())){
                     enterprise.setId(dbEnterprise.getId());
                    baseMapper.updateById(enterprise);
                }else {
                    // 没添加过就是添加
                    baseMapper.insert(enterprise);
                }
            }
        }

    }

    @Override
    public Enterprise getInfo(String code) {

        QueryWrapper<Enterprise> wrapper = new QueryWrapper<>();
        wrapper.eq("code",code);
        Enterprise enterprise = baseMapper.selectOne(wrapper);
        String name = cmnClient.getDictById(Long.valueOf(enterprise.getOrgtype())).getName();
        enterprise.setOrgtype(name);

        return enterprise;
    }
}
